<template>
  <view class="hb-p-4">
    <Paglist
      v-model="dataList"
      :params="{ id: props.id }"
      :is-init-api="true"
      :is-show-loadmore="false"
      @register="register"
    >
      <template v-for="item in dataList" :key="item.id">
        <MemberItem
          :item="item"
          :show-setting="roleType !== RoleTypeEnum.MEMBER"
          @click="handleToAiChatPage(item)"
          @setting="handleSetting"
        />
      </template>
    </Paglist>
  </view>
</template>

<script setup lang="ts">
  import { circleMemberList, removeCircleMember } from '@/api/contact';
  import { CircleMemberListResult } from '@/api/contact/types';
  import { useConList } from '@/components/Paglist/useConList';
  import MemberItem from '../../components/MemberItem.vue';
  import { RoleTypeEnum } from '@/enums/LoginEnum';
  import { Toast } from '@/utils';

  const props = defineProps<{
    id: number;
    roleType: RoleTypeEnum;
    updateMemberNum: (type: 'add' | 'subtract', num: number) => void;
  }>();

  const dataList = ref<CircleMemberListResult[]>([]);
  const [register, { refresh }] = useConList({ api: circleMemberList });
  provide('api', null);

  /** 成员设置 */
  const handleSetting = (item: CircleMemberListResult) => {
    const itemList = ['成员设置'];
    if (
      (props.roleType === RoleTypeEnum.ADMIN && item.roleType === RoleTypeEnum.MEMBER) ||
      (props.roleType === RoleTypeEnum.SUPER_ADMIN && item.roleType !== RoleTypeEnum.SUPER_ADMIN)
    ) {
      itemList.push('移出圈子');
    }
    uni.showActionSheet({
      itemList,
      success: ({ tapIndex }) => {
        if (tapIndex) {
          handleRemoveCircleMember(item);
          return;
        }
        navigateTo({
          name: 'circleMemberSetting',
          options: {
            memberId: item.id,
            success: () => {
              refresh();
            },
          },
        });
      },
    });
  };

  function handleRemoveCircleMember(item: CircleMemberListResult) {
    uni.showModal({
      title: '移出圈子',
      content:
        '确定要把ta移出圈子吗？移出后ta将无法再使用圈子知识库匹配圈子资源，ta共享的文件将从知识库移除。',
      confirmText: '确认移出',
      cancelColor: '#999996',
      cancelText: '取消',
      confirmColor: '#EA5E0E',
      success: ({ confirm }) => {
        if (confirm) {
          removeCircleMember({ memberId: item.id }).then(() => {
            props.updateMemberNum('subtract', 1);
            Toast('移出成功');
            refresh();
          });
        }
      },
    });
  }

  const handleToAiChatPage = (item: CircleMemberListResult) => {
    navigateTo({
      name: 'aiChatPage',
      options: { uuid: item.botUUid },
    });
  };
  defineExpose({
    refresh,
  });
</script>

<style scoped></style>
